package com.yang.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionFactory {
	
	/** 数据库连接地址*/
	private  static String DB_URL ;
	/** 数据库连接驱动 */
	private  static String DB_DRIVER;
	/** 数据库用户名 */
	private  static String DB_USERNAME;
	/** 数据库密码 */
	private  static String DB_PASSWORD;
	
	private static final ConnectionFactory factory = new ConnectionFactory();
	
	private Connection connection;
	/**
	 * 静态代码块，只执行一次
	 * 加载配置文件
	 */
	static{
		Properties prop = new Properties();
		try{
			InputStream inputStream = ConnectionFactory.class.getClassLoader()
					.getResourceAsStream("com/yang/properties/dbconfig.properties");
			prop.load(inputStream);
		}catch(Exception e){
			System.out.println("=============加載配置文件出错=============");
		}
		DB_URL = prop.getProperty("db_url");
		DB_DRIVER = prop.getProperty("db_driver");
		DB_USERNAME = prop.getProperty("db_uesr");
		DB_PASSWORD = prop.getProperty("db_pasword");
	}
	
	private ConnectionFactory(){
		
	}
	
	/**
	 * 单例模式获取factory
	 * @return
	 */
	public static ConnectionFactory getInstance(){
		return factory;
	}
	
	/**
	 * 获取数据库连接
	 * @return
	 */
	public Connection getConnection(){
		try {
			Class.forName(DB_DRIVER);
			connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}
	
	/**
	 * 关闭数据库连接等
	 * @param result
	 * @param ps
	 * @param conn
	 */
	public void close(ResultSet result, PreparedStatement ps,Connection conn) {
		try {
			if (result != null) {
				result.close();
				result = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (ps != null) {
					ps.close();
					ps = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				try {
					if (conn != null) {
						conn.close();
						conn = null;
					}
				} catch (SQLException e) {
					e.printStackTrace();
				} 
			}
		}
	}
}
